from odoo.http import request, Response
from odoo import http, Command
from odoo.addons.api_manager.tools.check_token import check_token
from odoo.addons.api_manager.tools.create_records import create_records
import logging
import json, re
from odoo import fields, _
from odoo.exceptions import ValidationError

_logger = logging.getLogger(__name__)


class ApiSubcontractingApply(http.Controller):

    @http.route("/v1.0/sb_api/subcontracting/apply", auth='public', type='http', methods=['post'], csrf=False)
    @check_token
    def subcontracting_apply(self, **kwargs):
        _logger.info('mes同步外发申请...')
        request.env.uid = 2
        data = request.httprequest.get_json()
        result = {
            'json': True,
            'data': {}
        }
        api_result = {
            'code': 0,
            'message': 'success'
        }
        params = data.get('params')
        # public user，无法操作，使用admin
        request.env.uid = 2
        try:
            mes_order = params.get('mes_order')
            line_ids = params.get('line_ids')
            workflow_id = request.env.ref('sb_subcontracting.product_subcontracting_workflow')
            line_vals = [] # 单工序外发
            multi_line_vals = [] # 多工序外发
            for l in line_ids:
                t = l.get('type') # 0单工序外发，1多工序外发
                if not int(t):
                    production_code = l.get('production_code')
                    workorder_code = l.get('workorder_code')
                    wo = self.get_workorder(production_code, workorder_code)
                    remark = self._get_work_remarks(wo)
                    line_vals.append((0, 0, {
                        'production_id': wo.production_id.id,
                        'workorder_id': wo.id,
                        'product_id': wo.production_id.product_id.id,
                        'remark': remark,
                        'qty': int(l.get('qty'))
                    }))
                else:
                    production_code = l.get('production_code')
                    start_workorder_code = l.get('start_workorder_code')
                    stop_workorder_code = l.get('stop_workorder_code')
                    # s_product_code = l.get('s_product_code')
                    start_wo = self.get_workorder(production_code, start_workorder_code)
                    stop_wo = self.get_workorder(production_code, stop_workorder_code)
                    workorders_str = ','.join(l.get('workorder_list', []))
                    service_code = start_wo.production_id.product_id.default_code + '-' + workorders_str
                    product = request.env['product.product'].search([('default_code', '=', service_code)], limit=1)
                    if not product:
                        raise ValidationError('未查询到服务产品, 产品编码: {}'.format('s_product_code'))
                    else:
                        product = request.env['product.product'].create([{'name': service_code,
                                                                          'default_code': service_code,
                                                                          'multi_workorder_subcontracting': True,
                                                                          'detailed_type': 'service'}])
                    multi_line_vals.append((0, 0, {
                        'production_id': start_wo.production_id.id,
                        'workorder_id': start_wo.id,
                        'start_workorder_id': start_wo.id,
                        'stop_workorder_id': stop_wo.id,
                        'product_id': product.id,
                        'remark': workorders_str,
                        'qty': int(l.get('qty')),
                        'done_act_qty': int(l.get('qty'))
                    }))

            if line_vals:
                record = request.env['sb.subcontracting.apply'].create({
                    'sb_workflow_template_id': workflow_id.id,
                    'mes_order': mes_order,
                    'line_ids': line_vals
                })
                record.create_workflow()
                for line in record.line_ids:
                    line.onchange_qty()
            if multi_line_vals:
                record = request.env['sb.subcontracting.apply'].create({
                    'sb_workflow_template_id': workflow_id.id,
                    'is_all_outside': True,
                    'mes_order': mes_order,
                    'line_ids': multi_line_vals
                })
                # record.create_workflow()
        except Exception as e:
            api_result['message'] = '{}'.format(e)
            api_result['code'] = -1
            request.env.cr.rollback()
        result['data'] = api_result
        result_json = json.dumps(result, ensure_ascii=False)
        create_records(result_json)
        return Response(result_json)

    def get_workorder(self, production_code, workorder_code):
        sql = """
                SELECT mw.id FROM mrp_workorder as mw, mrp_production as mp, mrp_workcenter as mc  
                WHERE mw.production_id=mp.id
                and mw.workcenter_id=mc.id
                and mp.name='{}'
                and mc.code='{}';
            """.format(production_code, workorder_code)
        cr = request.env.cr
        cr.execute(sql)
        wid = cr.fetchall()
        if not wid:
            raise ValidationError('未查询到相关工序: {}-{}'.format(production_code, workorder_code))
        if len(wid) > 1:
            raise ValidationError('查询到工序不唯一：{}-{}'.format(production_code, workorder_code))
        wo = request.env['mrp.workorder'].sudo().search([('id', '=', list(wid[0])[0])])
        return wo

    def _get_work_remarks(self, workorder_id):
        if not workorder_id:
            return ''
        str_list = []
        cs_area = 0
        ss_area = 0
        for line in workorder_id.operation_id.param_line_ids:
            str_list.append(f'{line.attribute_id.name}:{line.value_id.name}')
            if 'C面金面积' in line.attribute_id.name:
                cs_area = re.findall(r'\d+', line.value_id.name)
            if 'S面金面积' in line.attribute_id.name:
                ss_area = re.findall(r'\d+', line.value_id.name)
        try:
            enig_area = float('.'.join(cs_area)) + float('.'.join(ss_area))
        except Exception as e:
            enig_area = 0
        return ';'.join(str_list), enig_area